<template>
    <div class="login">
      <van-nav-bar title="登录" left-arrow left-text="返回"  @click-left="$router.go(-1)"/>
      <div class="container">
        <div class="title">
          <h3>手机号登录</h3>
          <p>未注册的手机号登录后将自动注册</p>
        </div>

        <div class="form">
          <div class="form-item">
            <input v-model="phone" type="text" placeholder="请输入手机号" maxlength="11" class="inp"/>
          </div>
          <div class="form-item">
            <input v-model="imgCode" type="text" placeholder="请输入图形验证码" maxlength="5" class="inp"/>
            <img v-if="imgUrl" :src="imgUrl" @click="getImgCodes" class="img" alt="">
          </div>
          <div class="form-item">
            <input v-model="smsCode" type="text" placeholder="请输入短信验证码" class="inp"/>
            <button class="btn" @click="getCodes">
              {{ seconds === totalSeconds ? '获取验证码' : `${seconds}秒后重发` }}
            </button>
          </div>
        </div>

        <div @click="logins" class="login-btn">登录</div>
      </div>
    </div>
    
  </template>
  
  <script setup lang="ts">
  import { getImgCode, getCode, login } from '@/api/login';
  import { showToast } from 'vant';
  
  import { ref, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { useUserStore } from '@/stores/user';

  const router = useRouter()
  const route = useRoute()
  const userStore = useUserStore()

  // 用户输入的图片验证码
  const imgCode = ref('');
  // 图片验证码key
  const imgKey = ref('');
  // 图片验证码url
  const imgUrl = ref('');
  // 短信验证码倒计时
  const totalSeconds = ref(60);
  // 短信验证码当前秒数
  const seconds = ref(60);
  // 手机号
  const phone = ref('');
  // 短信验证码 
  const smsCode = ref('');

  const getImgCodes = async () => {
    const {data:{base64, key}} = await getImgCode()
    
    imgKey.value = key;
    imgUrl.value = base64;
  }

  // 验证 手机号 图形验证码
  const valiFn = () => {
    // 手机号验证
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(phone.value)) {
      showToast('请输入正确的手机号');
      return false;
    }

    // 图形验证码验证
    const imgCodeReg = /^[a-zA-Z0-9]{4}$/;
    if (!imgCodeReg.test(imgCode.value)) {
      showToast('请输入4位图形验证码');
      return false;
    }

    return true;
  }

  // 获取短信验证码
  const getCodes = async () => {
    if(!valiFn()){
      return;
    }

    const res = await getCode(imgCode.value, imgKey.value, phone.value);
    showToast('短信发送成功,请注意查收')

    // 倒计时
    let timer = setInterval(() => {
      seconds.value--;
      if(seconds.value === 0){
        seconds.value = totalSeconds.value;
        clearInterval(timer);
      }
    }, 1000);
  }

  // 登录
  const logins = async () => {
    if(!valiFn()){
      return;
    }
    // 短信验证码验证
    const smsCodeReg = /^\d{6}$/;
    if (!smsCodeReg.test(smsCode.value)) {
      showToast('请输入6位短信验证码');
      return false;
    }

    try {
      const res = await login(phone.value, smsCode.value);
      console.log(res)
      if(res.status === 200) {
        showToast('登录成功');

        const { data:{ userId, token} } = res
        userStore.setToken(userId)
        userStore.setUserId(token)

        // 登录成功后跳转到首页
        // 判断是否带参数,如果是其他页面拦截来的登录页面,则跳转到拦截页面
        const redirectUrl = route.query.redirect || '/'
        router.push(redirectUrl)
      }
    } catch (error) {
      showToast('登录失败');
    }
  }
  
  onMounted(() => {
    getImgCodes();
  })
  
  </script>
  
  <style scoped lang="scss">
  .van-nav-bar {
    :deep(.van-icon){
      color: #333;
    }
  }
  .container{
    padding: 49px 29px;
    .title{
      margin-bottom: 30px;
      h3 {
        font-size: 26px;
        color: #333;
        font-weight: 500;
      }
      p {
        font-size: 14px;
        color: #999;
      }
    }
    .form{
      .form-item{
        position: relative;
        margin-bottom: 20px;
        .inp{
          width: 100%;
          height: 40px;
          border: 1px solid #ccc;
          border-radius: 5px;
          padding-left: 10px;
          font-size: 14px;  
          color: #333;
          outline: none;
          box-sizing: border-box;
          &::placeholder{
            color: #999;
          }
          &:focus{
            border-color: #ff9211;
          }
          &:focus::placeholder{
            color: #ff9211;
          }
        }
        .img{
          position: absolute;
          width: 100px;
          height: 40px;
          right: 0px;
          top: 0px;
          border-radius: 5px;
          cursor: pointer;
        }
        .btn{
          position: absolute;
          width: 100px;
          height: 40px;
          right: 0px;
          top: 0px;
          border-radius: 5px;
          border: none;
          font-size: 14px;
          font-weight: 500;
          color: #fff;
          background: linear-gradient(90deg, #ecb53c, #ff9211);
          box-shadow: 0 0 10px rgba(236, 181, 60, 0.5);
          cursor: pointer;
        }
      }
    }
    .login-btn{
        width: 100%;
        height: 42px;
        margin-top: 39px;
        border-radius: 39px;
        background: linear-gradient(90deg, #ecb53c, #ff9211);
        box-shadow: 0 0 10px rgba(236, 181, 60, 0.5);
        color: #fff;
        font-size: 14px;
        font-weight: 500;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
      }
  }

  </style>
  
  